package uform.ui.assembler;
import uform.model.core.IValueHandler;
import uform.ui.comp.Repeater;
import uform.model.cell.ArrayCell;
import uform.ui.comp.Component;        
using StringTools;

class ArrayCellAssembler extends BaseAssembler<ArrayCell<IValueHandler<Dynamic>>>
{
	static var re = ~/^\[(\d+)\]/;
	override public function assemble(cell : ArrayCell<IValueHandler<Dynamic>>) : Component
	{                                 
		var rt = root;
		var r = new Repeater("", function() return rt.assemble(cell.type), cell.min, cell.max);
		
		var m = form.model;
		
		form.model.onChange.add(function(e) {
			var epath = e.path;
			var rpath = r.path();
			if (epath.startsWith(rpath) && re.match(epath.substr(rpath.length)))
			{
				var pos = Std.parseInt(re.matched(1));
				if (r.items.length <= pos)
				{
					r.createMany(pos + 1 - r.items.length);
					m.set(epath, e.value);
				}
				return;
			} else if(epath != rpath)
				return;
			var arr : Array<Dynamic> = e.value; 
            var len = null == arr ? 0 : arr.length;
			while(r.items.length > len)
				r.delete();
			r.createMany(len-r.items.length);
			
			for(i in 0...len)
			{
				m.set(rpath + "[" + i + "]", arr[i]);
			}
		});  
		
		r.items.onRemove.add(function(e) {
			var path = r.path(); 
			var arr : Array<Dynamic> = m.get(path);
			if(null == arr)
				return;                
			arr = arr.splice(e.pos, 1);
			m.onChange.dispatch({ path : path + "[R]", value : e.pos });
		});

		r.items.onInsert.add(function(index) {
			var path = r.path() + "[" + index + "]";
			var value = m.get(path);
			if(null == value)
				m.set(path, null);
		});

		return r;
	}     
}